<template>
  <div class="document-setting">
    <document-nav-bar current="documentSetting" />
    <div class="document-setting-main" v-loading="pendding">

      <div class="document-setting-select-item">
        <div class="document-setting-switch-item">
          <div class="document-select-title">
            <h4>{{$t('wiki.setting.documentSetting.label1')}}</h4>
            <div>{{$t('wiki.setting.documentSetting.des1')}}</div>
          </div>
          <el-switch
            v-model="wikiConfig.needApprove"
            @change="changeState($event, 'needApprove')"
            :active-text="wikiConfig.needApprove ? $t('common.base.enable') : $t('common.base.disable')"
          ></el-switch>
        </div>
        <div class="document-allot-executor-header-row" v-if="wikiConfig.needApprove">
          <!-- <base-select-user-input 
            v-model="wikiConfig.approvers" 
            multiple 
            :collapse="false"
          >
          </base-select-user-input> -->
          <biz-form-remote-select
            class="user-type-select"
            ref="TeamUserBizFormRemoteSelect"
            v-model="wikiConfig.approvers"
            
            :placeholder="$t('common.placeholder.select')"
            :remote-method="fetchUsers"
            multiple
          >
            <div
              class="allot-users-option"
              slot="option"
              slot-scope="{ option }"
            >
              <contact-user-item
                :user="option"
                :show-user-state="true"
                :state-color="stateColor"
                :show-tag="true"
              />
            </div>
          </biz-form-remote-select>
          
          <el-button type="primary" @click="approversSave">{{$t('common.base.save')}}</el-button>
        </div>
      </div>

      <div class="document-setting-switch-item">
        <div>
          <h4>{{$t('wiki.setting.documentSetting.label2')}}</h4>
          <div>{{$t('wiki.setting.documentSetting.des2')}}</div>
        </div>
        <el-switch
          v-model="wikiConfig.permitShare"
          @change="changeState($event, 'permitShare')"
          :active-text="wikiConfig.permitShare ? $t('common.base.enable') : $t('common.base.disable')"
        ></el-switch>
      </div>

      <div class="document-setting-switch-item">
        <div>
          <h4>{{$t('wiki.setting.documentSetting.label3')}}</h4>
          <div>
            {{$t('wiki.setting.documentSetting.des3')}}
          </div>
        </div>
        <el-switch
          v-model="wikiConfig.relevantRecommend"
          @change="changeState($event, 'relevantRecommend')"
          :active-text="
            wikiConfig.relevantRecommend ? $t('common.base.enable') : $t('common.base.disable')
          "
        ></el-switch>
      </div>

      <div class="document-setting-switch-item">
        <div>
          <h4>{{$t('wiki.setting.documentSetting.label4')}}</h4>
          <div>{{$t('wiki.setting.documentSetting.des4')}}</div>
        </div>
        <el-switch
          v-model="wikiConfig.comment"
          @change="changeState($event, 'comment')"
          :active-text="
            wikiConfig.comment ? $t('common.base.enable') : $t('common.base.disable')
          "
        ></el-switch>
      </div>

      <div class="document-setting-switch-item">
        <div>
          <h4>{{$t('wiki.setting.documentSetting.label8')}}</h4>
          <div>{{$t('wiki.setting.documentSetting.des15')}}</div>
        </div>
        <el-switch
          v-model="wikiDownloadAuth"
          @change="changeDownloadBth"
          :active-value="1"
          :inactive-value="0"
          :active-text="wikiDownloadAuth ? $t('common.base.enable') : $t('common.base.disable')"
        ></el-switch>
      </div>

      <div class="document-setting-select-item" v-if="_isShowTaskModule">
        <div>
          <h4>{{$t('wiki.setting.documentSetting.label5')}}</h4>
          <!-- <div>如果启用该选项，知识库将辅助业务执行，可在处理业务过程中流快速沉淀知识库，且在业务处理过程中推荐相关知识库</div> -->
        </div>
        <div class="document-setting-select-item-checkbox">
          <el-checkbox v-model="wikiConfig.taskFunction" @change="changeState($event, 'taskFunction')">
            <span>{{$t('wiki.setting.documentSetting.label6')}}</span>
            <el-tooltip :content="$t('wiki.setting.documentSetting.des5')" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            <el-button
              @click="exampleDialogVisible = true"
              type="text"
              class="view-example"
            >
              {{$t('common.base.checkTemplate')}}
            </el-button>
          </el-checkbox>
        </div>
      </div>

      <div class="document-setting-table">
        <div class="document-setting-switch-item document-setting-table-header">
          <div>
            <h4>{{$t('wiki.setting.documentSetting.label7')}}</h4>
            <div>{{$t('wiki.setting.documentSetting.des6')}}</div>
          </div>
          <el-switch
            v-model="wikiConfig.outsideSearch"
            @change="changeState($event, 'outsideSearch')"
            :active-text="
              wikiConfig.outsideSearch ? $t('common.base.enable') : $t('common.base.disable')
            "
          ></el-switch>
        </div>

        <el-table
          :data="searchRuleList"
          v-if="wikiConfig.outsideSearch"
          stripe
          header-row-class-name="common-list-table-header__v2"
          :empty-text="$t('wiki.setting.documentSetting.tips1')"
        >
          <el-table-column
            prop="num"
            width="50"
            :label="$t('common.base.SN')"
            align="center"
          ></el-table-column>
          <el-table-column prop="name" width="150" :label="$t('common.base.name')" align="center">
          </el-table-column>
          <el-table-column prop="link" :label="$t('common.base.link')" align="center">
          </el-table-column>
          <el-table-column :label="$t('common.base.operation')" align="center" width="200">
            <template slot-scope="{ $index, row }">
              <i class="el-icon-edit" @click="editRule(row)"></i>
              <i class="el-icon-close" @click="deleteRule(row)"></i>
              <i
                class="iconfont icon-long-arrow-up"
                @click="moveRule($index, row.id, 'up')"
              ></i>
              <i
                class="iconfont icon-long-arrow-down"
                @click="moveRule($index, row.id, 'down')"
              ></i>
            </template>
          </el-table-column>
          <el-table-column :label="`${$t('common.base.enable')}/${$t('common.base.disable')}`" align="center" width="100" :resizable="false">
            <template slot-scope="{row}">
              <el-switch
                :active-value="1"
                :inactive-value="0"
                @change="ruleswitchEnable($event, row)"
                v-model="row.state"
              ></el-switch>
            </template>
          </el-table-column>
        </el-table>
        <el-button class="outside-search-create" v-if="wikiConfig.outsideSearch" type="primary" @click="createRule" icon="el-icon-plus">{{$t('common.base.addModule', {module:''})}}</el-button>
      </div>
    </div>

    <!-- 站外搜索新建编辑框 -->
    <outsideSearchDialog ref="outsideSearchDialog" />
    <base-modal :title="$t('wiki.setting.documentSetting.title1')" :show.sync="exampleDialogVisible" width="872px" class="wiki-example-dialog">
      <img :src="wikiExample1" :alt="$t('wiki.setting.documentSetting.des7')">
      <img :src="wikiExample2" :alt="$t('wiki.setting.documentSetting.des8')">
      <div slot="footer">
        <el-button
          type="primary"
          @click="exampleDialogVisible = false"
          size="small"
        >{{$t('common.base.iKnow')}}</el-button>
      </div>
    </base-modal>
  </div>
</template>

<script>
import documentNavBar from "../components/documentNavBar";
import ContactUserItem from "@src/component/common/BaseContact/ContactUserItem.vue";
import outsideSearchDialog from "./components/outsideSearchDialog";
import { switchWikiOutsideSearch, saveWikiSetting, getApproverList, wikiApproversSave, getAllWikiOutsideSearch, deleteWikiOutsideSearch, moveWikiOutsideSearch } from "@src/api/SettingApi.ts";
import http from "@src/util/http";
import { getLocalesOssUrl } from '@src/util/assets'
const wikiExample1 = getLocalesOssUrl('/task/wikiExample1.png')
const wikiExample2 = getLocalesOssUrl('/task/wikiExample2.png')
import _ from 'lodash';
/** api */
import * as settingApi from '@src/api/SettingApi'
/* mixin */
import { VersionControlTaskMixin } from '@src/mixins/versionControlMixin'

const WIKI_DOWNLOAD_CODE = 'wikiDownloadAuth'

export default {
  name: "document-setting",
  mixins: [VersionControlTaskMixin],
  components: {
    documentNavBar,
    ContactUserItem,
    outsideSearchDialog,
  },
  inject: ['initData'],
  data() {
    return {
      pendding: false,
      wikiConfig: this.updateConfig(this.initData?.wikiConfig, 'get'),
      params: {
        keyword: "",
        pageNum: 1,
      },
      searchRuleList: [],
      stateColor: {}, // 用户工作状态颜色
      exampleDialogVisible: false,

      wikiExample1,
      wikiExample2,
      wikiDownloadAuth: 0,
    };
  },
  // inject: ["initData"],
  computed: {
  },
  mounted() {
    this.initializeStateColor();
    // todo 初始值
    this.init();
    this.fetchConfig()
  },
  methods: {
    /** 获取是否允许下载附件内容的配置 */
    async fetchConfig() {
      try {
        const { data = [], success, message } = await settingApi.getTenantConfigByCodeList({ codeList: [WIKI_DOWNLOAD_CODE] })
        if(!success) return this.$message.warning(message)
        this.wikiDownloadAuth = data.find(item=> item.configCode === WIKI_DOWNLOAD_CODE)?.isOpen ?? 0;
      } catch(err) {
        console.error('[getTenantConfigByCodeList error]', err)
      }
    },
    /** 点击允许下载附件内容 */
    async changeDownloadBth() {
      try {
        const params = {
          code: WIKI_DOWNLOAD_CODE,
          isOpen: this.wikiDownloadAuth,
          configNumValue: 0
        }
        const { success, message = '' } = await settingApi.updateTenantConfigById(params)
        if(!success) {
          this.$message.error(message)
        }
      } catch(err) {
        console.error('[updateTenantConfigById error]', err)
      }
    },
    // 获取初始化数据
    init() {
      this.getAllWikiOutsideSearch()
    },

    async getAllWikiOutsideSearch() {
      try {
        const result = await getAllWikiOutsideSearch();
        if (result.succ) {
          this.searchRuleList = result.data;
          this.searchRuleList.forEach(
            (item, index) => (item.num = index + 1)
          );
        }
      } catch (error) {
        console.error("get dispatch rules error", error);
      }
    },

    // 开关状态更变
    async changeState(e, key) {
      try {
        const params = {
          flow: key,
          state: e,
        };
        let result = await saveWikiSetting(params);
        if (result.succ && result.data?.wikiConfig) {
          this.wikiConfig = result.data?.wikiConfig || {}
          this.updateConfig(this.wikiConfig)
        }
      } catch (error) {
        console.error("save setting config state error", error);
      }
    },

    // 新建站外搜索规则
    createRule() {
      if (this.searchRuleList.length >= 10) {
        return this.$message({
          showClose: true,
          duration: 1500,
          message: this.$t('wiki.setting.documentSetting.des9'),
          type: "warning"
        });
      }
      this.$refs.outsideSearchDialog.openDialog("create")
    },

    // 编辑站外搜索规则
    editRule(row) {
      if (row.isDefault) {
        return this.$message({
          showClose: true,
          duration: 1500,
          message: this.$t('wiki.setting.documentSetting.des10'),
          type: "error",
        })
      }
      this.$refs.outsideSearchDialog.openDialog("edit", row)
    },

    // 删除站外搜索规则
    async deleteRule(row) {
      try {
        if (row.isDefault) {
          return this.$message({
            showClose: true,
            duration: 1500,
            message: this.$t('wiki.setting.documentSetting.des11'),
            type: "error"
          });
        }

        if (!(await this.$platform.confirm(this.$t('wiki.setting.documentSetting.des12')))) return

        const params = { id: row.id }
        const result = await deleteWikiOutsideSearch(params)
        if (result.status === 0) {
          this.$message({
            showClose: true,
            duration: 1500,
            message: this.$t('common.base.tip.deleteSuccess'),
            type: "success"
          });
          this.getAllWikiOutsideSearch()
        } else {
          this.$message({
            showClose: true,
            duration: 1500,
            message: result.message,
            type: "error"
          })
        }
      } catch (error) {
        console.error("delete rule error", error)
      }
    },

    // 移动站外搜索规则table数据
    async moveRule(index, id, operation) {
      try {
        if (index === 0 && operation === "up") return
        if (index === this.searchRuleList.length - 1 && operation === "down") return

        let param = { id, operation }

        const result = await moveWikiOutsideSearch(param);
        if (result.succ) {
          this.getAllWikiOutsideSearch();
        } else {
          this.$message({
            showClose: true,
            duration: 1500,
            message: result.message,
            type: "error",
          });
        }
      } catch (error) {
        console.log(error)
        console.error("delete remark error");
      }
    },

    // 更改表格开关状态
    async ruleswitchEnable(state, row) {
      if(this.searchRuleList.filter(v => v.state === 1).length > 5) {
        this.$message({
          message: this.$t('wiki.setting.documentSetting.des13'),
          type: "error",
        });
        this.$set(row, 'state', state ? 0 : 1) // 重置开关
        return
      }
      if(this.searchRuleList.filter(v => v.state === 1).length === 0) {
        this.$message({
          message: this.$t('wiki.setting.documentSetting.des14'),
          type: "error",
        });
        this.$set(row, 'state', state ? 0 : 1) // 重置开关
        return
      }
      const params = {
        id: row.id,
        state
      };
      let result = await switchWikiOutsideSearch(params);
      if (result.succ) {
        this.getAllWikiOutsideSearch();
      } else {
        this.$message({
          showClose: true,
          duration: 1500,
          message: result.message,
          type: "error",
        })
      }
    },

    // 查询用户列表
    fetchUsers(params) {
      let { keyword, pageNum } = params
      this.params = {
        pageNum,
        keyword,
      }

      return getApproverList(this.params).then((res) => {
        if (!res || !res.list) return;

        res.list = res.list.map((item) =>
          Object.freeze({
            label: item?.displayName || "",
            value: item?.userId || "",
            ...item,
          })
        )

        return res;
      })
    },

    async approversSave() {
      try {
        let userIds = (this.wikiConfig.approvers || []).map(item => item.userId).join(',')
        let params = { userIds }

        const result = await wikiApproversSave(params)
        
        if (result.succ) {
          this.updateConfig(result.data?.wikiConfig)
          this.$message({
            showClose: true,
            duration: 1500,
            message: result.message,
            type: "success"
          })
        } else {
          this.$message({
            showClose: true,
            duration: 1500,
            message: result.message,
            type: "error",
          });
        }
      } catch (error) {
        console.log(error)
        console.error("save approvers error")
      }
    },

    /** 初始化工作状态的颜色 */
    initializeStateColor() {
      http
        .get("/setting/getStateColorMap")
        .then(
          (res) => (this.stateColor = _.assign({}, this.stateColor, res || {}))
        )
        .catch((err) => console.error(err));
    },

    getInitConfig() {
      return {
        approvers: [],
        comment: false,
        defaultNoticeTypesGenerated: false,
        defaultWikiTypesGenerated: false,
        needApprove: true,
        outsideSearch: false,
        permitShare: false,
        relevantRecommend: false
      }
    },

    updateConfig(config, type = 'set') {
      config?.approvers?.forEach(v => {
        v.label = v.displayName
        v.value = v.userId
      })
      let data = config || this.getInitConfig()
      if (type === 'get') {
        return data
      }
      this.wikiConfig = data
    }
  },
};
</script>

<style lang="scss" scoped>
.document-setting {
  display: flex;
  min-height: 100vh;
  padding: 12px;

  .document-setting-main {
    min-width: 730px;
    margin-left: 13px;
    padding: 20px;
    width: 100%;
    background: #ffffff;
    border-radius: 4px;
  }

  .document-setting-switch-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
  }

  .document-setting-table {
    // padding-left: 20px;

    .document-setting-table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
    }

    i {
      cursor: pointer;
      font-size: 13px;
      color: #909399;
    }
  }

  .document-setting-select-item {
    .document-allot-executor-header-row {
      display: flex;
      align-items: center;
      max-width: 80%;

      .el-button {
        margin-left: 10px;
      }

      .base-select-container .list-wrapper {
        height: 200px;
      }
    }
  }
}

h4 {
  padding: 0;
  font-size: 15px;
}

.user-type-select ::v-deep .list-wrapper {
  width: calc(80% - 287px);
  left: auto;
  // height: 300px;
  // overflow: hidden;
}

.outside-search-create {
  margin-top: 16px;
}
.document-setting-select-item-checkbox {
  // margin-top: 12px;
  margin-bottom: 32px;
  .view-example {
    padding: 0;
  }
}

::v-deep .el-checkbox__label {
  font-size: 0;
  & > span {
    vertical-align: auto;
    font-size: 14px;
    font-weight: 400;
    color: #595959;
    line-height: 22px;
  }
  .el-icon-question {
    position: relative;
    vertical-align: auto;
    font-size: 14px;
    color: #595959;
    margin: 0 8px;
  }
}

.wiki-example-dialog {
  ::v-deep .el-dialog__body {
    height: 466px;
    overflow: auto;
    img {
      height: auto;
    }
    img:first-child {
      margin-bottom: 24px;
    }
  }
}
</style>
